﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UITest.Extension;
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UITesting.WpfControls;

namespace CodedUITestExtensions
{
    /// <summary>
    /// Extensions for WpfList.
    /// </summary>
    public static class WpfListExtensions
    {
        /// <summary>
        /// Gets list item collection.
        /// </summary>
        /// <param name="list">WpfList.</param>
        private static IList<T> GetListItemsEx<T>(this WpfList list) where T : WpfListItem
        {
            Type type = typeof(T);
            var listItem = (T)Activator.CreateInstance(type, list);
            IList<T> uiListItems = listItem.FindMatchingControls().Select(c =>
            {
                var item = (T)Activator.CreateInstance(type, list);
                item.CopyFrom(c);
                return item;
            }
            ).ToList();
            return uiListItems;
        }

        /// <summary>
        /// Select list item with given text.
        /// </summary>
        /// <param name="list">WpfList.</param>
        /// <param name="text">List item text.</param>
        /// <param name="predicate">Search condition.</param>
        public static void Select<T>(this WpfList list, string text, Func<T, string> predicate) where T : WpfListItem
        {
            IList<T> uiListItems = list.GetListItemsEx<T>();
            T itemForSelect = uiListItems.FirstOrDefault(item => predicate(item).Equals(text));
            if (itemForSelect == null)
            {
                throw new UITestControlNotFoundException("List item with text - " + text + " - wasn't found.");
            }
            Mouse.Click(itemForSelect);
        }
    }
}
